package huawei;

/**
 * 找单词
 */
public class Q93 {

    static char[][] chars = {{'A','C', 'C', 'F'},{'C', 'D', 'E', 'D'},{'B', 'E', 'S', 'S'},{'F','E','C','A'}};
    static int N = 4;
    static String target = "ACCESS";

    // 方向
    static int[][] direction = {{0,1},{1,0},{0,-1},{-1,0}};

    public static void main(String[] args) {

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if (chars[i][j] == target.charAt(0)) {
                    StringBuilder stringBuilder = new StringBuilder();
                    if (dfs(i, j, 0, stringBuilder)) {
                        System.out.println(stringBuilder);
                        return;
                    }
                }
            }
        }

        System.out.println("N");
    }

    public static boolean dfs(int i, int j, int ti, StringBuilder sb) {
        if (i < 0 || i >= N || j < 0 || j >= N) {
            return false;
        }

        if (ti == target.length()) {
            return true;
        }

        if (chars[i][j] != target.charAt(ti)) {
            return false;
        }


        sb.append(i).append(",").append(j).append(" ");

        for (int[] d : direction) {
            int x = i + d[0];
            int y = j + d[1];
            if (dfs(x, y, ti+1, sb)) {
                return true;
            }
        }

        sb.delete(sb.length() - 4, sb.length());

        return false;
    }
}
